<?php

namespace app\model;

use GatewayWorker\Lib\Gateway;
use plugin\webman\gateway\Events;
use support\Log;
use support\Redis;

class Base
{

    public static function curlpostdata($url, $post = '')
    {
        $ch = curl_init(); /////初始化一个CURL对象
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); ///设置不输出在浏览器上
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //50秒超时
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);  ////传递一个作为HTTP "POST"操作的所有数据的字符
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $content = curl_exec($ch);
        if (curl_errno($ch)) { //出错则显示错误信息
            return curl_error($ch);
        }
        $json = json_decode($content, true);
        return $json;
    }

    public static function gettoken()
    {
        $md = date("md");
        $tokenkey = "schoolwstoken{$md}";
        $token = self::redisGet($tokenkey);
        //  devlog($token);
        if (!$token) {

            $ipfile = "/server/log/ip.txt";

            try {
                $ipstr = file_get_contents($ipfile);
                //  devlog("file_get_contents ok({$ipfile})({$ipstr})");

            } catch (\Exception $e) {
                devlog("file_get_contents err");

                $handle = fopen($ipfile, "r"); //读取二进制文件时，需要将第二个参数设置成'rb'
                //通过filesize获得文件大小，将整个文件一下子读到一个字符串中
                $ipstr = fread($handle, filesize($ipfile));
                fclose($handle);
            }


            //  devlog($ipstr);
            // $pattern = '(192[.]168[.]\d{1,3}[.]\d{1,3})';
            $pattern = '(\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}/24)';

            preg_match($pattern, $ipstr, $out);
            $ip = "noip";
            if ($out) {


                $ip = $out[0];

                $ip = substr($ip, 0, -3);


                //  $ip=trim($ip,"\/24");
            } else {
            }

            $school_id = getenv("school_id");
            $post["school_id"] = $school_id;
            $post["ip"] = $ip;
            //      devlog("match ip:#{$ip}#");

            $host = getenv("host");
            // devlog('getschoolwstoken');
            $url = "{$host}api/lsods/getschoolwstoken";
            devlog($url);

            $rt = self::curlpost($url, $post);
            //   devlog('---------');

            if (!isset($rt["code"])) {
                devlog("返回无code:");
                devlog($rt);

                return "";
            }
            if ($rt["code"] == 0) {
                if (isset($rt["data"]["schoolwstoken"])) {
                    $token = $rt["data"]["schoolwstoken"];
                    devlog("set schoolwstoken success ({$token})");

                    self::redisSet($tokenkey, $token, 3600 * 7);
                } else {
                    devlog("no schoolwstoken");
                    devlog($rt);
                    sleep(60);
                }
            }
        }
        return $token;
    }

    /***$url 地址 ￥post_file 提交的内容*/
    public static function curlpost($url, $post)
    {

        $school_id = getenv("school_id");
        $post["school_id"] = $school_id;
        $post["noncestr"] = getenv("noncestr");
        $post["timestamp"] = time();

        $strarr = [];
        foreach ($post as $k => $v) {
            $strarr[] = "{$k}={$v}";
        }
        $tmpStr = implode("&", $strarr);
        $signature = sha1($tmpStr);
        $post["sign"] = $signature;


        $json = self::curlpostdata($url, $post);
        return $json;
    }

    public static function redisIncr($key)
    {
        $value = Redis::incr($key);
        return $value;
    }

    public static function redisGet($key)
    {
        $value = Redis::get($key);

        return $value;
    }

    public static function redisSetArr($key, $data, $t = 0)
    {
        self::redisSet($key, json_encode($data), $t);
    }

    public static function redisGetArr($key)
    {

        $value = self::redisGet($key);
        $data = json_decode($value, true);
        return $data;
    }

    public static function redisSet($key, $data, $t = 0)
    {
        if ($t) {
            Redis::set($key, $data, "ex", $t);
        } else {
            Redis::set($key, $data);
        }
    }
    //
    //    public static function getrobotlist()
    //    {
    //        $robotlist = [];
    //        $robotinfokey = "robotinfo:*";
    //
    //        $robotkeylist = Redis::keys($robotinfokey);
    //
    //        if (!$robotkeylist) {
    //            //   devlog("first getrobotlist");
    //
    //            $host = getenv("host");
    //            $url = "{$host}api/lsods/getrobotlist";
    //
    //
    //            $school_id = getenv("school_id");
    //            $post["school_id"] = $school_id;
    //            $rt = Base::curlpost($url, $post);
    //            // devlog($rt);
    //            if ($rt["code"] == 0) {
    //                $robotlist = $rt["data"]["robotlist"];
    //                if ($robotlist) {
    //                    foreach ($robotlist as $robotk => $robotv) {
    //                        //   devlog($robotv);
    //                        $imei = $robotv["imei"];
    //                        $robotkey = "robotinfo:{$imei}";
    //                        $robotinfo = Base::redisGetArr($robotkey);
    //                        if (!$robotinfo) {
    //                            if (!isset($robotv["coach_id"])) {
    //                                devlog("init no coach_id");
    //                            }
    //
    //                            $robotv["call_status"] = Events::ROBOT_FREE;
    //                            $robotv["status"] = Events::ROBOT_OFFLINE;
    //                            $robotv["error_list"] = self::getErrorListByImei($imei);
    //                            $robotv["student_id"] = 0;
    //                            $robotv["student_name"] = "";
    //                            $robotv["errnum"] = 0;
    //                            $robotv["backcolor"] = "green";
    //                            $robotv["nomc"] = 0;
    //                            Base::redisSetArr($robotkey, $robotv);
    //                        }
    //
    //
    //                    }
    //                } else {
    //                    $toastmsg = "当前驾校（{$school_id}）机器人数量=0";
    //
    //                    Base::toast($toastmsg);
    //                }
    //
    //
    //            } else {
    //                $robotlist = [];
    //            }
    //
    //        } else {
    //
    //            foreach ($robotkeylist as $key) {
    //                $key = trim($key, "swoft:");
    //                $robotinfo = Base::redisGetArr($key);
    //                $robotlist[] = $robotinfo;
    //            }
    //
    //        }
    //        //     devlog("getrobotlist finish");
    //        return $robotlist;
    //    }
    public static function getrobotlist()
    {
        $robotlist = [];
        $robotinfokey = "robotinfo:*";

        $robotkeylist = Redis::keys($robotinfokey);

        if (!$robotkeylist) {
            devlog("first getrobotlist");

            $host = getenv("host");
            $url = "{$host}api/lsods/getrobotlist";
            $school_id = getenv("school_id");
            $post["school_id"] = $school_id;
            $rt = self::curlpost($url, $post);
            if (!$rt) {
                return [];
            }


            if (!isset($rt["code"])) {
                devlog("getrobotlist no code");
                devlog($rt);
                return [];
            }
            //   devlog($rt);
            if ($rt["code"] == 0) {
                $robotlist = $rt["data"]["robotlist"];
                if ($robotlist) {
                    foreach ($robotlist as $robotk => $robotv) {
                        //   devlog($robotv);
                        $subject = $robotv["subject"];


                        $imei = $robotv["imei"];
                        $robotkey = "robotinfo:{$imei}";
                        $robotinfo = self::redisGetArr($robotkey);
                        if (!$robotinfo) {
                            if (!isset($robotv["coach_id"])) {
                                devlog("init no coach_id");
                            }
                            $robotv["call_status"] = Events::ROBOT_FREE;
                            $robotv["status"] = Events::ROBOT_OFFLINE;
                            $robotv["error_list"] = self::getErrorListByImei($imei);
                            $robotv["student_id"] = 0;
                            $robotv["student_name"] = "";
                            $robotv["errnum"] = 0;
                            $robotv["school_id"] = $robotv["school_id"];
                            $robotv["backcolor"] = "green";
                            $robotv["nomc"] = 0;
                            self::redisSetArr($robotkey, $robotv);
                        }
                    }
                } else {
                    $toastmsg = "当前驾校（{$school_id}）机器人数量=0";
                    devlog($toastmsg);

                    self::toast($toastmsg);
                }
            } else {
                $robotlist = [];
            }
        } else {

            foreach ($robotkeylist as $key) {
                $key = trim($key, "swoft:");
                $robotinfo = self::redisGetArr($key);
                $robotlist[] = $robotinfo;
            }
        }

        return $robotlist;
    }
    //    public static function getsub3robotlist()
    //    {
    //        $robotlist = [];
    //        $robotinfokey = "sub3robotinfo:*";
    //
    //        $robotkeylist = Redis::keys($robotinfokey);
    //
    //        if (!$robotkeylist) {
    //
    //
    //            $host = getenv("host");
    //            $url = "{$host}api/lsods/getsub3robotlist";
    //            $school_id = getenv("school_id");
    //            $post["school_id"] = $school_id;
    //            $rt = self::curlpost($url, $post);
    //            if(!$rt){
    //                return [];
    //            }
    //            //   devlog($rt);
    //            if ($rt["code"] == 0) {
    //                $robotlist = $rt["data"]["robotlist"];
    //                if ($robotlist) {
    //                    foreach ($robotlist as $robotk => $robotv) {
    //                        //   devlog($robotv);
    //                        $imei = $robotv["imei"];
    //                        $robotkey = "sub3robotinfo:{$imei}";
    //                        $robotinfo = self::redisGetArr($robotkey);
    //                        if (!$robotinfo) {
    //                            if (!isset($robotv["coach_id"])) {
    //                                devlog("init no coach_id");
    //                            }
    //                            $robotv["call_status"] = Events::ROBOT_FREE;
    //                            $robotv["status"] = Events::ROBOT_OFFLINE;
    //                            $robotv["student_id"] = 0;
    //                            $robotv["student_name"] = "";
    //
    //                            self::redisSetArr($robotkey, $robotv);
    //                        }
    //
    //
    //                    }
    //                } else {
    //                    $toastmsg = "当前驾校（{$school_id}）机器人数量=0";
    //
    //                    self::toast($toastmsg);
    //                }
    //
    //
    //            } else {
    //                $robotlist = [];
    //            }
    //
    //        } else {
    //
    //            foreach ($robotkeylist as $key) {
    //                $key = trim($key, "swoft:");
    //                $robotinfo = self::redisGetArr($key);
    //                $robotlist[] = $robotinfo;
    //            }
    //
    //        }
    //
    //        return $robotlist;
    //    }
    public static function getErrorList()
    {
        $error_list_key = "error_list_key";
        $WrongJudgeArr = self::redisGetArr($error_list_key);

        if (!$WrongJudgeArr) {
            $host = getenv("host");
            $url = "{$host}api/lsods/geterrlist";
            $post = [];
            $rt = self::curlpost($url, $post);
            if ($rt["code"] == 0) {
                $WrongJudgeArr = $rt["data"]["list"];
                self::redisSetArr($error_list_key, $WrongJudgeArr, 3600 * 24);
            }
        }
        return $WrongJudgeArr;
    }

    public static function getErrorListByImei($robotimei)
    {
        $new3errcode = Base::redisGetArr('stuCarNewNumberErrorArr' . $robotimei);





        $WrongJudgeArr = Base::getErrorList();
        $noalert = [];
        $WrongJudge = [];
        $point_code = 0;
        $passcode = "";
        foreach ($WrongJudgeArr as $key => $v) {
            $suralert = $v["suralert"];

            if ($suralert == 0) {
                $noalert[] = $v['code'];
            }
            $WrongJudge[$v['code']] = $v['point'];
        }


        $errorCodeArr = [];
        if ($new3errcode) {
            foreach ($new3errcode as $k => $v) {
                $errid = $v["errcode"];
                $vstudent_name = $v["student_name"];
                if (!isset($WrongJudge[$errid])) {
                    continue;
                }
                if (!empty($errid)) {
                    $code3 = str_pad(substr($errid, 0, 3), 8, "0", STR_PAD_RIGHT);
                    $code5 = str_pad(substr($errid, 0, 5), 8, "0", STR_PAD_RIGHT);
                    $err3 = isset($WrongJudge[$code3]) ? $WrongJudge[$code3] : "未知项目:{$code3}"; //项目
                    $err5 = isset($WrongJudge[$code5]) ? $WrongJudge[$code5] : "未知阶段:{$code5}"; //阶段
                    $err = isset($WrongJudge[$errid]) ? $WrongJudge[$errid] : "未知错误:{$errid}"; //错误
                    // $errorCodeArr[] = '[' . $err3 . '] 一> ' . $err5 . ' :                              ' . $err;
                    $errorCodeArr[] = "{$vstudent_name}[{$err3}]一>{$err5}:{$err}";
                }
            }
        }


        return $errorCodeArr;
    }


    public static function pushJson($rdata, $fd)
    {
        //    devlog($rdata);

        if (!is_string($rdata)) {
            if (!isset($rdata["data"]["msgid"])) {
                //     $rdata["data"]["msgid"] = 0;
                $cmd = $rdata["data"]["cmd"];
                $rdata["data"]["fd"] = $fd;

                $msg = $rdata["msg"];

                //   $key = "pushJsonsurid:{$cmd}:{$fd}";
                $key = "pushJsonid:{$cmd}:{$fd}";
                $broadcastsurid = Base::redisIncr($key);
                $rdata["data"]["msgid"] = $broadcastsurid;
                if ($cmd == "surcallin") {

                    $timekey = "{$key}:{$broadcastsurid}";

                    Base::redisSet($timekey, time(), 60 * 5);
                    devlog("surcallin:{$msg}:{$broadcastsurid}");
                }
            }
        }


        //    devlog($rdata);
        $rtjson = json_encode($rdata);
        return Gateway::sendToClient($fd, $rtjson);
    }

    public static function errlog($message)
    {
        $school_id = getenv("school_id");


        $url = "http://report.kuaiyazhineng.com/api/ea/rec";
        $postdata["content"] = $message;
        $postdata["host"] = "lds";
        $postdata["uri"] = "$school_id";
        $postdata["ip"] = "";
        self::curlpost($url, $postdata);
    }

    public static function getSurinfoByImei($imei, $rm = false)
    {
        $surinfokey = "SurinfoByImei:{$imei}";
        if ($rm) {
            Redis::del($surinfokey);
        }

        $surinfo = self::redisGetArr($surinfokey);

        if (!$surinfo) {

            $host = getenv("host");
            $url = "{$host}api/lsods/getsurinfobyimei";
            $post["imei"] = $imei;
            $rt = self::curlpost($url, $post);
            if ($rt["code"] == 0) {
                $surinfo = $rt["data"]["surinfo"];


                self::redisSetArr($surinfokey, $surinfo);
            }
        }

        return $surinfo;
    }

    public static function broadcastsur($rdata)
    {
        $surveillancelistkey = "surveillancelist";
        $surveillancelist = self::redisGetArr($surveillancelistkey);


        if ($surveillancelist) {
            foreach ($surveillancelist as $surveillanceinfo) {
                $surveillancefd = $surveillanceinfo["fd"];


                self::pushJson($rdata, $surveillancefd); //broadcastsur
            }
        }
    }
    public static function broadcastsub3sur($rdata)
    {
        $surveillancelistkey = "sub3surveillancelist";
        $surveillancelist = self::redisGetArr($surveillancelistkey);

        if ($surveillancelist) {
            foreach ($surveillancelist as $surveillanceinfo) {
                $surveillancefd = $surveillanceinfo["fd"];


                self::pushJson($rdata, $surveillancefd); //broadcastsur
            }
        }
    }
    public static function toast($toastmsg, $imei = "")
    {

        $surdata["msg"] = "$toastmsg";
        $surdata["code"] = 0;

        $surdata["data"]["cmd"] = "toast";
        $surdata["data"]["coach_id"] = 0;
        $surdata["data"]["imei"] = $imei;

        self::broadcastsur($surdata);
    }

    public static function toasttofd($surfd, $toastmsg, $imei = "")
    {
        $surdata["msg"] = "$toastmsg";
        $surdata["code"] = 0;

        $surdata["data"]["cmd"] = "toast";
        $surdata["data"]["coach_id"] = 0;
        $surdata["data"]["imei"] = $imei;


        self::pushJson($surdata, $surfd); //toasttofd
    }

    public static function getCoachByStudent($student_id)
    {

        if (!$student_id) {
            return 0;
        }
        $key = "getCoachByStudent:{$student_id}";

        // 快鸭驾校按预约来

        $coachinfo = self::redisGetArr($key);
        if (!$coachinfo) {
            $host = getenv("host");
            $url = "{$host}api/lsods/getcoachbystudent";
            $post["student_id"] = $student_id;
            $rt = self::curlpost($url, $post);

            if (isset($rt["code"]) && $rt["code"] == 0) {

                $coachinfo = $rt["data"]["coachinfo"];
                self::redisSet($key, $coachinfo, 60);
            }
        }

        return $coachinfo;
    }
    public static function getSub3RobotinfoByImei($imei)
    {
        self::getrobotlist();
        $robotkey = "robotinfo:{$imei}";
        $robotinfo = self::redisGetArr($robotkey);


        if (!isset($robotinfo["imei"])) {
            $robotinfo = [];
        }
        if (!$robotinfo) {
            $host = getenv("host");
            $url = "{$host}api/lsods/getsub3robotinfobyimei";
            $post["imei"] = $imei;
            $rt = self::curlpost($url, $post);
            if ($rt["code"] == 0) {
                $robotinfo = $rt["data"]["robotinfo"];

                $robotinfo["call_status"] = Events::ROBOT_FREE; //是否能呼叫
                $robotinfo["status"] = Events::ROBOT_OFFLINE; //是否 在线
                $robotinfo["student_name"] = "";


                $robotkey = "robotinfo:{$imei}";
                self::redisSetArr($robotkey, $robotinfo);
            }
        }
        return $robotinfo;
    }


    //1 机器人 2路考仪
    public static function getRobotCoachinfoByImei($imei, $type = 1)
    {
        self::getrobotlist();
        $robotkey = "robotinfo:{$imei}";
        $robotinfo = self::redisGetArr($robotkey);


        if (!isset($robotinfo["imei"])) {
            $robotinfo = [];
        }
        if (!$robotinfo) {
            $host = getenv("host");
            $url = "{$host}api/lsods/getrobotinfobyimei";
            $post["imei"] = $imei;
            $post["type"] = $type;
            $rt = self::curlpost($url, $post);
            if ($rt["code"] == 0) {
                $robotinfo = $rt["data"]["robotinfo"];
                $robot_id = $robotinfo["robot_id"];
                devlog("getRobotCoachinfoByImei");
                devlog($robotinfo);
                $robotinfo["call_status"] = Events::ROBOT_FREE; //是否能呼叫
                $robotinfo["status"] = Events::ROBOT_OFFLINE; //是否 在线
                $robotinfo["student_name"] = "";
                $robotinfo["error_list"] = self::getErrorListByImei($imei);

                //master_school_id
                $robotinfo["errnum"] = 0;
                $robotinfo["nomc"] = 0;
                $robotinfo["backcolor"] = "green";

                $robotkey = "robotinfo:{$imei}";
                self::redisSetArr($robotkey, $robotinfo);
            }
        }
        return $robotinfo;
    }


    public static function alert($alertmsg, $imei = "")
    {
        $surdata["msg"] = "$alertmsg";
        $surdata["code"] = 0;

        $surdata["data"]["cmd"] = "alert";
        $surdata["data"]["coach_id"] = 0;
        $surdata["data"]["imei"] = $imei;

        self::broadcastsur($surdata);
    }
}
